﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Services.Production;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services.Production;

internal sealed class CardInfoService : ICardInfoService
{
    private readonly IDBManager _dbManager;

    public CardInfoService(IDBManager db) => _dbManager = db;

    public bool Exist(string cardNo)
    {
        using var db = _dbManager.Create();
        return db.Exists<CardInfo>("CardNo = @0", cardNo);
    }

    public Task<List<CardInfo>> GetAllAsync()
    {
        using var db = _dbManager.Create();
        return db.FetchAsync<CardInfo>();
    }

    public async Task<(List<CardInfo> items, int count)> GetPagedAsync(CardInfo filter, int pageIndex, int pageItems)
    {
        var sql = new Sql();
        if (!string.IsNullOrEmpty(filter.CardNo))
        {
            sql.Where("CardNo Like @0", $"%{filter.CardNo}%");
        }

        if (filter.PLevel != null)
        {
            sql.Where("PLevel = @0", filter.PLevel);
        }

        using var db = _dbManager.Create();
        var data = await db.PageAsync<CardInfo>(pageIndex, pageItems, sql);
        return (data.Items, Convert.ToInt32(data.TotalItems));
    }

    public async Task AddCardInfoAsync(CardInfo model)
    {
        model.CreatedAt ??= DateTime.Now;

        using var db = _dbManager.Create();
        await db.InsertAsync(model);
    }

    public async Task UpdateCardInfoAsync(CardInfo model)
    {
        model.UpdatedAt = DateTime.Now;

        using var db = _dbManager.Create();
        await db.UpdateAsync<CardInfo>("SET PLevel=@PLevel, Owner=@Owner, Description=@Description, IsEnabled=@IsEnabled, UpdatedAt=@UpdatedAt WHERE Id=@Id", model);
    }
}
